import {
  ADD_TO_CART,
  ADD_COUNTER,
} from "@/store/mutation-types";

export default {
  addCart(context, payload) {
    return new Promise((resolve, reject) => {
      //此处的payload为新添加的商品
      // let oldProduct = null;
      // for (let item of state.cartList) {
      //   if (item.iid === payload.iid) {
      //     oldProduct = item;
      //   }
      // }
      //
      // //判断oldProduct是否有值
      // if (oldProduct) {
      //   oldProduct.count += 1;
      // } else {
      //   payload.count = 1;
      //   state.cartList.push(payload);
      // }


      //数组常用的方法有哪些？ push/pop/unshift/shift/sort/reverse/join/map/filter/reduce


      // 1.查找数组中是否有该商品
      let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)
      // 2.判断oldProduct是否有值
      if (oldProduct) {  //商品数量+1
        // oldProduct.count += 1;
        context.commit(ADD_COUNTER, oldProduct)
        resolve('当前商品的数量+1');
      } else {  //添加新的商品
        payload.count = 1;
        // context.state.cartList.push(payload);
        context.commit(ADD_TO_CART, payload)
        resolve('在购物车中添加了新的商品~')
      }
    })
  }
}
